package me.seu.demo.service;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.entity.Item;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * es store
 *
 * @author  liangfeihu
 * @since  2023/6/30 14:42
 */
@Slf4j
@Service
public class ElasticsearchServiceImpl {

    @Resource(name = "coElasticsearchClient")
    private ElasticsearchClient coElasticsearchClient;

    public void saveItem(Item item) throws IOException {
        final String index = "item_123456789_2023-6";
        IndexRequest<Item> indexRequest = new IndexRequest.Builder<Item>()
                .index(index)
                .id(item.getId().toString())
                .document(item)
                .build();
        IndexResponse response = coElasticsearchClient.index(indexRequest);
    }

    public void saveItems(List<Item> itemList) throws IOException {
        final String index = "item_123456789_2023-6";
        BulkRequest.Builder bulkRequestBuilder = new BulkRequest.Builder();
        itemList.stream()
                .filter(item -> CharSequenceUtil.isNotEmpty(item.getTitle()))
                .forEach(item -> bulkRequestBuilder.operations(operation -> operation
                        .index(builder -> builder
                                .index(index)
                                .document(item)
                        )
                ));

        BulkResponse response = coElasticsearchClient.bulk(bulkRequestBuilder.build());
        if (response.errors()) {
            for (BulkResponseItem item : response.items()) {
                if (ObjectUtil.isNotNull(item.error())) {
                    // todo 存在没有保存成功的数据怎么办
                    log.error("Send pointValues to elasticsearch error: {}", item.error().reason());
                }
            }
        }
    }

}